/**
 * Copyright © 2016-2023 The Thingsboard Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.thingsboard.server.queue.discovery;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.thingsboard.common.util.SystemUtil;
import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.TbTransportService;
import org.thingsboard.server.common.data.util.CollectionsUtil;
import org.thingsboard.server.common.msg.queue.ServiceType;
import org.thingsboard.server.gen.transport.TransportProtos;
import org.thingsboard.server.gen.transport.TransportProtos.ServiceInfo;
import org.thingsboard.server.queue.util.AfterContextReady;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import static org.thingsboard.common.util.SystemUtil.getCpuCount;
import static org.thingsboard.common.util.SystemUtil.getCpuUsage;
import static org.thingsboard.common.util.SystemUtil.getDiscSpaceUsage;
import static org.thingsboard.common.util.SystemUtil.getMemoryUsage;
import static org.thingsboard.common.util.SystemUtil.getTotalDiscSpace;
import static org.thingsboard.common.util.SystemUtil.getTotalMemory;


@Component
@Slf4j
public class DefaultTbServiceInfoProvider implements TbServiceInfoProvider {

    @Getter
    @Value("${service.id:#{null}}")
    private String serviceId;

    @Getter
    @Value("${service.type:monolith}")
    private String serviceType;

    @Getter
    @Value("${service.rule_engine.assigned_tenant_profiles:}")
    //已分配租户配置文件
    private Set<UUID> assignedTenantProfiles;

    @Autowired
    //程序上下文
    /**
     * ApplicationContext是由BeanFactory派生而来的，当ApplicationContext在初始化应用上下文的时候就会实例化所有的Bean，
     * 而BeanFactory在做实例化应用上下文的时候不会初始化Bean，只有当Bean被访问的时候才会进行实例化
     */
    private ApplicationContext applicationContext;

    private List<ServiceType> serviceTypes;
    private ServiceInfo serviceInfo;

    /**
     * init方法上使用了@PostConstruct标记，当spring启动的时候会自动调用
     * 这里的init的最终目的就是生成出serviceInfo结构体
     */
    @PostConstruct
    public void init() {
        if (StringUtils.isEmpty(serviceId)) {
            try {
                //获取本机的HostName作为serviceId，当前理解serviceId的作用是为了集群部署进行识别
                serviceId = InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                //如果找不到启动tb的机器的HostName那么生成一个10为的由英文字母（不区分大小写）组成的随机字符串作为serviceId
                serviceId = StringUtils.randomAlphabetic(10);
            }
        }
        log.info("Current Service ID: {}", serviceId);
        //暂时不知道serviceType的含义，目前的理解是启动的服务包含什么类型
        if (serviceType.equalsIgnoreCase("monolith")) {
            //serviceTypes被赋值为一个不可变集合，unmodifiableList保证集合所在的地址不可变，集合内部的元素也不可变
            //unmodifiableList是通过随机读写保证的
            //如果serviceType的值是monolith，那么servicesTypes的值将会包含  TB_CORE, TB_RULE_ENGINE, TB_TRANSPORT, JS_EXECUTOR, TB_VC_EXECUTOR
            serviceTypes = Collections.unmodifiableList(Arrays.asList(ServiceType.values()));
        } else {
            serviceTypes = Collections.singletonList(ServiceType.of(serviceType));
        }
        //初始化租户配置UUID，如果不包含规则引擎或者租户的配置是空的
        if (!serviceTypes.contains(ServiceType.TB_RULE_ENGINE) || assignedTenantProfiles == null) {
            assignedTenantProfiles = Collections.emptySet();
        }

        //通过系统信息生成服务信息
        generateNewServiceInfoWithCurrentSystemInfo();
    }

    /**
     * @AfterContextReady用于标记一个方法，指定被标记的方法在ApplicaitonContext处理完成后才执行
     */
    @AfterContextReady
    public void setTransports() {
        serviceInfo = ServiceInfo.newBuilder(serviceInfo)
                .addAllTransports(getTransportServices().stream()
                        .map(TbTransportService::getName)
                        .collect(Collectors.toSet()))
                .build();
    }

    private Collection<TbTransportService> getTransportServices() {
        return applicationContext.getBeansOfType(TbTransportService.class).values();
    }

    @Override
    public ServiceInfo getServiceInfo() {
        return serviceInfo;
    }

    @Override
    public boolean isService(ServiceType serviceType) {
        return serviceTypes.contains(serviceType);
    }

    @Override
    public ServiceInfo generateNewServiceInfoWithCurrentSystemInfo() {
        //构建出ServiceInfo对象并设置属性字段
        ServiceInfo.Builder builder = ServiceInfo.newBuilder()
                .setServiceId(serviceId)
                .addAllServiceTypes(serviceTypes.stream().map(ServiceType::name).collect(Collectors.toList()))
                 //设置系统信息到结构体
                .setSystemInfo(getCurrentSystemInfoProto());
        if (CollectionsUtil.isNotEmpty(assignedTenantProfiles)) {
            builder.addAllAssignedTenantProfiles(assignedTenantProfiles.stream().map(UUID::toString).collect(Collectors.toList()));
        }
        return serviceInfo = builder.build();
    }

    private TransportProtos.SystemInfoProto getCurrentSystemInfoProto() {
        TransportProtos.SystemInfoProto.Builder builder = TransportProtos.SystemInfoProto.newBuilder();

        SystemUtil.getCpuUsage().ifPresent(builder::setCpuUsage); //设置cpu的用法
        SystemUtil.getMemoryUsage().ifPresent(builder::setMemoryUsage); //设置内存的用噶
        SystemUtil.getDiscSpaceUsage().ifPresent(builder::setDiskUsage); //设置磁盘的用法

        SystemUtil.getCpuCount().ifPresent(builder::setCpuCount); //设置cpu的数量
        SystemUtil.getTotalMemory().ifPresent(builder::setTotalMemory); //设置内存的总数
        SystemUtil.getTotalDiscSpace().ifPresent(builder::setTotalDiscSpace); //设置磁盘的空间

        return builder.build();
    }

}
